<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */

namespace App\Controller\Admin;

use App\Controller\AppBaseController;
use App\Model\News;
use App\Model\Notify;
use App\Model\Study;
use App\Model\StudyColumn;

use App\Model\StudyColumnCategory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\AdminApiAuth;

#[Controller(prefix: 'admin')]
#[Middleware(AdminApiAuth::class)]
class StudyController extends AppBaseController
{

    /**
     * 后台--学习天地栏目列表
     * @return object
     */
    #[RequestMapping(path:'studyColumnList',methods: 'get')]
    public function studyColumnList(): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $where['status'] = 1;
            $list = StudyColumn::where($where)->selectRaw('id,name,type,status')->get();
            $next = 0;
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }

    /**
     * 后台--学习天地栏目详情
     * @param int $column_id
     * @return object
     */
    #[RequestMapping(path:'studyColumnInfo/{column_id}',methods: 'get')]
    public function studyColumnInfo(int $column_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $where['status'] = 1;
            $where['id'] = $column_id;
            $info = StudyColumn::where($where)->first();
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 学习天地栏目发布|编辑
     * @param int|null $column_id
     * @return object
     */
    #[RequestMapping(path: 'studyColumnEdit[/{column_id}]',methods: 'post,get')]
    public function studyColumnEdit(int|null $column_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){
//                $data['name'] = 'xxxxxxx';
//                $data['is_banner'] = 1;
//                $data['banner_photo'] = 'fqxinyi23/test/xyWords/xyWords1691110928830.jpg';
//                $data['link_url'] = 'https://www.baidu.com';
//                $data['status'] = 1;
//            }
            //虚拟数据


            //默认特殊专栏
            $data['type'] = 1;
            if(empty($data['name'])) return $this->reMsg->re(10007);
            if(empty($data['link_url'])) $data['link_url'] = null; //增加外部链接
            empty($data['is_banner']) || !is_numeric($data['is_banner']) ? $data['is_banner'] = 0 : $data['is_banner'] = 1;
            empty($data['status']) || !is_numeric($data['status']) ? $data['status'] = 0 : $data['status'] = 1;


            //指定支部（不指定党支部）
            if($_admin->level==1){
//                if(empty($data['party_id'])) return $this->reMsg->re(10007);
//                $party_id = $data['party_id'];
                $party_id = $_admin->party_id;
            }else{
                $party_id = $_admin->party_id;
            }

            //验证权限（超级管理员）
            if($_admin->level!=1) return $this->reMsg->re(10009);

            if($column_id){
                //编辑
                $info = StudyColumn::where('id',$column_id)->first();
                if(empty($info)) return $this->reMsg->re(10008);
                $info->type = $data['type'];
                $info->name = $data['name'];
                $info->is_banner = $data['is_banner'];
                $info->banner_photo = $data['banner_photo'];
                $info->link_url = $data['link_url'];
                $info->status = $data['status'];
                $info->party_id = $party_id;
                $info->admin_id = $_admin->id;
                $info->save();
                return $this->reMsg->re(1);
            }else{
                $data['party_id'] = $party_id;
                $data['admin_id'] = $_admin->id;
                $insertRet = StudyColumn::create($data);
                if($insertRet){
                    return $this->reMsg->re(1);
                }else{
                    return $this->reMsg->re(0);
                }
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }




    /**
     * 学习天地栏目|删除
     * @param int $column_id
     * @return object
     */
    #[RequestMapping(path:'studyColumnDelete/{column_id}',methods: 'get')]
    public function studyColumnDelete(int $column_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //判断信息
            $info = StudyColumn::where('id',$column_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限（超级管理员）
            if($_admin->level!=1) return $this->reMsg->re(10009);
            //查询该栏目下是否存在 学习天地内容
            $studyList = Study::where('column_id',$column_id)->first();
            if($studyList){
                return $this->reMsg->re(0,'该栏目存在内容，不可删除');
            }
            $info->delete();
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }




    /**
     * 学习天地栏目|小分类列表
     * @param int $column_id
     * @return object
     */
    #[RequestMapping(path:'studyColumnCategoryList/{column_id}',methods: 'get')]
    public function studyColumnCategoryList(int $column_id = 0): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            //判断信息
            $where['status'] = 1;
            if(is_numeric($column_id) && in_array($column_id,[1,2,3])){
                $where['column_id'] = $column_id;
            }
            $list = StudyColumnCategory::where($where)
                ->selectRaw('id,name,column_id,status')
                ->orderByDesc('id')
                ->get();
            $next = 0;
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--学习天地栏目|小分类|详情
     * @param int $category_id
     * @return object
     */
    #[RequestMapping(path:'studyColumnCategoryInfo/{category_id}',methods: 'get')]
    public function studyColumnCategoryInfo(int $category_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $where['status'] = 1;
            $where['id'] = $category_id;
            $info = StudyColumnCategory::where($where)->first();
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }

    /**
     * 后台--学习天地栏目|小分类|编辑
     * @param int|null $category_id
     * @return object
     */
    #[RequestMapping(path: 'studyColumnCategoryEdit[/{category_id}]',methods: 'post,get')]
    public function studyColumnCategoryEdit(int|null $category_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){
//                $data['column_id'] = 1';
//                $data['name'] = 1;
//                $data['status'] = 1;
//            }
            //虚拟数据


            //默认特殊专栏
            if(empty($data['column_id']) || !is_numeric($data['column_id'])
                || empty($data['name']))
            {
                return $this->reMsg->re(10007);
            }
            empty($data['status']) || !is_numeric($data['status']) ? $data['status'] = 0 : $data['status'] = 1;

            //指定支部（不指定党支部）
            if($_admin->level==1){
//                if(empty($data['party_id'])) return $this->reMsg->re(10007);
//                $party_id = $data['party_id'];
                $party_id = $_admin->party_id;
            }else{
                $party_id = $_admin->party_id;
            }

            //验证权限（超级管理员）
            if($_admin->level!=1) return $this->reMsg->re(10009);

            if($category_id){
                //编辑
                $info = StudyColumnCategory::where('id',$category_id)->first();
                if(empty($info)) return $this->reMsg->re(10008);
                $info->column_id = $data['column_id'];
                $info->name = $data['name'];
                $info->status = $data['status'];
                $info->party_id = $party_id;
                $info->admin_id = $_admin->id;
                $info->save();
                return $this->reMsg->re(1);
            }else{
                $data['party_id'] = $party_id;
                $data['admin_id'] = $_admin->id;
                $insertRet = StudyColumnCategory::create($data);
                if($insertRet){
                    return $this->reMsg->re(1);
                }else{
                    return $this->reMsg->re(0);
                }
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--学习天地栏目|小分类|删除
     * @param int $category_id
     * @return object
     */
    #[RequestMapping(path:'studyColumnCategoryDelete/{category_id}',methods: 'get')]
    public function studyColumnCategoryDelete(int $category_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //判断信息
            $info = StudyColumnCategory::where('id',$category_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限（超级管理员）
            if($_admin->level!=1) return $this->reMsg->re(10009);
            //查询该栏目下是否存在 学习天地内容
            $studyList = Study::where('column_cate_id',$category_id)->first();
            if($studyList){
                return $this->reMsg->re(0,'该栏目分类存在内容，不可删除');
            }
            $info->delete();
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }




    /**
     * 后台--学习天地列表   type 1：理论学习 2:党建文件 3：廉政教育
     * @return object
     */
    #[RequestMapping(path:'studyList',methods: 'post,get')]
    public function studyList(): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //其他参数
            $column_id = $this->request->input('column_id', 1);
            $column_cate_id = $this->request->input('column_cate_id', 1);

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where = [];
            //指定支部
            if($_admin->level==1){
                $party_id = $this->request->input('party_id', null);
                if($party_id){
                    $where['party_id'] = $party_id;
                }
            }else{
                $where['party_id'] = $_admin->party_id;
            }


            if($column_id){
                $where['column_id'] = $column_id;
            }

            if($column_cate_id){
                $where['column_cate_id'] = $column_cate_id;
            }
            $list = Study::with(['party'=>function($query){
                    $query->selectRaw('id,name')->get();
                },'column'=>function($query){
                    $query->selectRaw('id,name')->get();
                },'columnCategory'=>function($query){
                    $query->selectRaw('id,name')->get();
                }])->where($where)
                ->selectRaw('id,party_id,column_id,column_cate_id,title,created_at')
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = Study::where($where)->count();
                if(count($list)>$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--学习天地详情
     * @param int $study_id
     * @return object
     */
    #[RequestMapping(path:'studyInfo/{study_id}',methods: 'get')]
    public function studyInfo(int $study_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $info = Study::where('id',$study_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }

    /**
     * 学习天地发布|编辑
     * @param int|null $study_id
     * @return object
     */
    #[RequestMapping(path: 'studyEdit[/{study_id}]',methods: 'post,get')]
    public function studyEdit(int|null $study_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){
//                $data['party_id'] = 1;
//                $data['type'] = 2;
//                $data['column_id'] = 1;
//                $data['column_cate_id'] = 1;
//                $data['title'] = '或那个风格二个人哥哥';
//                $data['content'] = '学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习';
//                $data['media_list'] = [
//                    '0'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
//                    '1'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
//                ];
//                $data['file_list'] = [
//                    ['name'=>'ceshi1','url'=>'https://www.baidu.com'],
//                    ['name'=>'ceshi1','url'=>'https://www.baidu.com']
//                ];
//                $data['is_banner'] = 1;
//                $data['banner_photo'] = 'fqxinyi23/test/xyWords/xyWords1691110928830.jpg';
//                $data['link_url'] = 'https://www.baidu.com';
//                $data['is_show'] = 1;
//                $data['is_long'] = 0;
//                $data['show_start_at'] = '2024-09-01 12:12:12';
//                $data['show_end_at'] = '2024-09-01 12:12:12';
//                $data['status'] = 1;
//            }
            //虚拟数据

            if(empty($data['title'])) return $this->reMsg->re(10007);

            if(empty($data['column_cate_id']) || !is_numeric($data['column_cate_id'])) $data['column_cate_id'] = null;
            if(empty($data['photo'])) $data['photo'] = null;
            if(empty($data['content'])) $data['content'] = null;
            if(empty($data['media_list']) || !is_array($data['media_list'])) $data['media_list'] = [];
            if(empty($data['file_list']) || !is_array($data['file_list'])) $data['file_list'] = [];
            if(empty($data['banner_photo']) || !is_string($data['banner_photo'])) $data['banner_photo'] = null;
            if(empty($data['link_url'])) $data['link_url'] = null;
            if(isset($data['is_long']) && $data['is_long']==0){
                if(empty($data['show_start_at']) || empty($data['show_end_at'])) return $this->reMsg->re(10007);
            }else{
                $data['is_long'] = 1;
                $data['show_start_at'] = null;
                $data['show_end_at'] = null;
            }
            empty($data['is_banner']) || !is_numeric($data['is_banner']) ? $data['is_banner'] = 0 : $data['is_banner'] = 1;
            empty($data['is_show']) || !is_numeric($data['is_show']) ? $data['is_show'] = 0 : $data['is_show'] = 1;
//            empty($data['status']) || !is_numeric($data['status']) ? $data['status'] = 0 : $data['status'] = 1;
            $data['status'] = 1;

            //不指定支部
            if($_admin->level==1){
//                if(!isset($data['party_id']) || $data['party_id']==null) return $this->reMsg->re(10007);
//                $party_id = $data['party_id'];
                $party_id = $_admin->party_id;
            }else{
                $party_id = $_admin->party_id;
            }

            if($study_id){
                //编辑
                $info = Study::where('id',$study_id)->first();
                if(empty($info)) return $this->reMsg->re(10008);

                //判断是否有权操作
                if($_admin->level!=1 && $_admin->party_id!=$info->party_id) return $this->reMsg->re(10009);

                $info->column_id = $data['column_id'];
                $info->column_cate_id = $data['column_cate_id'];
                $info->title = $data['title'];
                $info->photo = $data['photo'];
                $info->content = $data['content'];
                $info->media_list = $data['media_list'];
                $info->file_list = $data['file_list'];
                $info->is_banner = $data['is_banner'];
                $info->banner_photo = $data['banner_photo'];
                $info->link_url = $data['link_url'];
                $info->is_show = $data['is_show'];
                $info->is_long = $data['is_long'];
                $info->show_start_at = $data['show_start_at'];
                $info->show_end_at = $data['show_end_at'];
                $info->status = $data['status'];
                $info->party_id = $party_id;
                $info->admin_id = $_admin->id;
                $info->save();

                //查询外链在news的状态
                /*if($data['is_show']==1){
                    $newsInfo = News::where('link_id',$info->id)->first();
                    if($newsInfo){
                        $newsInfo->title = $data['title'];
                        $newsInfo->photo = $data['photo'];
                        $newsInfo->link_url = $data['link_url'];
                        $newsInfo->is_long = $data['is_long'];
                        $newsInfo->show_start_at = $data['show_start_at'];
                        $newsInfo->show_end_at = $data['show_end_at'];
                        if($data['is_show']==1 && $data['status']==1){
                            $newsInfo->status = 1;
                        }else{
                            $newsInfo->status = 0;
                        }
                        $newsInfo->save();
                    }
                }*/
                return $this->reMsg->re(1);
            }else{
                $data['party_id'] = $party_id;
                $data['admin_id'] = $_admin->id;
                $insertRet = Study::create($data);
                if($insertRet){
                    //说明需要上学习发布首页显示，插入一条数据
                    /*if($data['is_show']==1){
                        $newsData['type'] = 4; //学习天地
                        $newsData['title'] = $data['title'];
                        $newsData['photo'] = $data['photo'];
                        $newsData['link_id'] = $insertRet->id;
                        $newsData['link_url'] = $data['link_url'];
                        $newsData['is_long'] = $data['is_long'];
                        $newsData['show_start_at'] = $data['show_start_at'];
                        $newsData['show_end_at'] = $data['show_end_at'];
                        if($data['is_show']==1 && $data['status']==1){
                            $newsData['status'] = 1;
                        }else{
                            $newsData['status'] = 0;
                        }
                        $newsData['admin_id'] = $_admin->id;
                        News::create($newsData);
                    }*/
                    return $this->reMsg->re(1);
                }else{
                    return $this->reMsg->re(0);
                }
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 学习天地|删除
     * @param int $study_id
     * @return object
     */
    #[RequestMapping(path:'studyDelete/{study_id}',methods: 'get')]
    public function studyDelete(int $study_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //判断信息
            $info = Study::where('id',$study_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限
            if($_admin->level!=1 && $_admin->party_id!=$info->party_id) return $this->reMsg->re(10009);
            $info->delete();

            //删除关联资讯
//            $newWhere['type'] = 4; //学习天地
//            $newWhere['link_id'] = $info->id;
//            $newInfo = News::where($newWhere)->first();
//
//            //删除关联资讯=》通知
//            $notifyWhere['module'] = 1;//学习天地（资讯过来的都是 module==1）
//            $notifyWhere['relation_id'] = $newInfo->id;
//            Notify::where($notifyWhere)->delete();
//
//            $newInfo->delete();

            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }





}